import sys, os

from PyQt4 import QtGui, QtCore, QtWebKit
from PyQt4.QtCore import QTimer

from editor import Editor
import config

class MainWindow(QtGui.QWidget):

    def __init__(self, parent):
        QtGui.QWidget.__init__(self)
        self._parent = parent
        self._refresh = True
        self._vbox = QtGui.QVBoxLayout(self)
        #Central Widgets
        self._hCentral = QtGui.QHBoxLayout()
        #Project Explorer
        self._tree = QtGui.QTreeWidget()
        self._tree.setFixedWidth(200)
        vboxTree = QtGui.QVBoxLayout()
        vboxTree.addWidget(self._tree)
        self._slider = QtGui.QSlider(QtCore.Qt.Horizontal)
        self._slider.setFixedWidth(200)
        self._slider.setRange(0, 30)
        self._slider.setSliderPosition(config.refresh/1000)
        self._labelRefresh = QtGui.QLabel('Seconds between refresh: ' + str(config.refresh/1000))
        vboxTree.addWidget(self._labelRefresh)
        vboxTree.addWidget(self._slider)
        self._hCentral.addLayout(vboxTree)
        #Editor
        self._layoutEditor = QtGui.QVBoxLayout()
        self._tabs = QtGui.QTabWidget()
        self._tabs.setTabsClosable(True)
        self._web = QtWebKit.QWebView()
        editor = Editor(self._web)
        self._tabs.addTab(editor, 'New Document')
        self._web.setFixedHeight(300)
        self._layoutEditor.addWidget(self._tabs)
        self._layoutEditor.addWidget(self._web)
        self._hCentral.addLayout(self._layoutEditor)
        self._vbox.addLayout(self._hCentral)
        #self._shortHideEditor = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_F2), self)
        shortHideWeb = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_F3), self)
        shortHideTree = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_F4), self)
        shortRefresh = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_F6), self)
        shortCloseTab = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_W), self)
        shortNew = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_N), self)
        shortOpen = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_O), self)
        shortSave = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_S), self)
        shortChangeTab = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_Tab), self)
        #self.connect(self._shortHideEditor, QtCore.SIGNAL("activated()"), self._showEditor)
        self.connect(shortHideWeb, QtCore.SIGNAL("activated()"), self._showWeb)
        self.connect(shortHideTree, QtCore.SIGNAL("activated()"), self._showTree)
        self.connect(shortRefresh, QtCore.SIGNAL("activated()"), self.manage_refresh)
        self.connect(shortCloseTab, QtCore.SIGNAL("activated()"), self.close_actual_tab)
        self.connect(shortNew, QtCore.SIGNAL("activated()"), self.new_editor)
        self.connect(shortOpen, QtCore.SIGNAL("activated()"), self.open_file)
        self.connect(shortSave, QtCore.SIGNAL("activated()"), self.save)
        self.connect(shortChangeTab, QtCore.SIGNAL("activated()"), self._change_tab)
        self.connect(self._tabs, QtCore.SIGNAL("currentChanged(int)"), self._tab_change)
        self.connect(self._slider, QtCore.SIGNAL("valueChanged(int)"), self._refresh_label_slider)

        #self._timer = QTimer(self)
        #self.connect(self._timer, QtCore.SIGNAL("timeout()"), self._refresh_preview)
        #self._timer.start(config.refresh)

    def _showWeb(self):
        self._web.setVisible(not self._web.isVisible())

    def _showEditor(self):
        self._tabs.setVisible(not self._tabs.isVisible())

    def _showTree(self):
        self._tree.setVisible(not self._tree.isVisible())

    def manage_refresh(self):
        self._refresh = not self._refresh
        if self._refresh:
            self._parent.setWindowTitle('Mango IDE - Preview Activated')
            self._render()
        else:
            self._parent.setWindowTitle('Mango IDE - Preview Desactivated')

    def _refresh_preview(self):
        self._web.setHtml(self.obtain_editor().toPlainText())

    def _refresh_label_slider(self, val):
        config.refresh = val * 1000
        self._labelRefresh.setText('Seconds between refresh: ' + str(config.refresh/1000))

    def obtain_editor(self):
        return self._tabs.widget(0)

    def new_editor(self):
        editor = Editor(self._web)
        self._tabs.addTab(editor, 'New Document')
        self._tabs.setCurrentIndex(self._tabs.count()-1)
        editor.setFocus()

    def open_file(self):
        fileName = str(QtGui.QFileDialog.getOpenFileName(self, 'Open File', filter='*.html'))
        if fileName == '':
            return
        editor = Editor(self._web)
        try:
            f = open(fileName)
            content = f.readlines()
            content = ''.join(content)
            editor.setPlainText(content)
            self._tabs.addTab(editor, 'New Document')
            self._tabs.setCurrentIndex(self._tabs.count()-1)
            editor.setFocus()
        except:
            QtGui.QMessageBox.information(self, 'Incorrect File', 'The file does not exist!')

    def open_project(self):
        folderName = str(QtGui.QFileDialog.getExistingDirectory(self, 'Open Project Directory'))
        if folderName == '':
            return
        editor = Editor(self._web)
        try:
            f = open(fileName)
            content = f.readlines()
            content = ''.join(content)
            editor.setPlainText(content)
            self._tabs.addTab(editor, 'New Document')
            self._tabs.setCurrentIndex(self._tabs.count()-1)
            editor.setFocus()
        except:
            QtGui.QMessageBox.information(self, 'Incorrect File', 'The file does not exist!')

    def close_actual_tab(self):
        self._tabs.removeTab(self._tabs.currentIndex())
        self._web.setHtml(self.obtain_editor().toPlainText())

    def save(self):
        editor = self.obtain_editor()
        try:
            if editor.newDocument:
                fileName = str(QtGui.QFileDialog.getSaveFileName(self, 'Save File', filter='*.html'))
                if fileName == '':
                    raise Exception()
                if not fileName.endswith('.html'):
                    fileName += '.html'
                self._tabs.setTabText(self._tabs.currentIndex(), os.path.basename(fileName))
                editor.newDocument = False
                editor.path = fileName
            else:
                fileName = editor.path
            f = open(fileName, 'w')
            f.write(editor.toPlainText())
            f.close()
        except:
            editor.newDocument = True
            editor.path = ''
            self._tabs.setTabText(self._tabs.currentIndex(), 'New Document')

    def save_as(self):
        editor = self.obtain_editor()
        try:
            fileName = str(QtGui.QFileDialog.getSaveFileName(self, 'Save File', filter='*.html'))
            if fileName == '':
                raise Exception()
            if not fileName.endswith('.html'):
                fileName += '.html'
            self._tabs.setTabText(self._tabs.currentIndex(), os.path.basename(fileName))
            editor.newDocument = False
            editor.path = fileName
            f = open(fileName, 'w')
            f.write(editor.toPlainText())
            f.close()
        except:
            editor.newDocument = True
            editor.path = ''
            self._tabs.setTabText(self._tabs.currentIndex(), 'New Document')

    def _tab_change(self, index):
        self._web.setHtml(self.obtain_editor().toPlainText())

    def _change_tab(self):
        if self._tabs.currentIndex() < (self._tabs.count()-1):
            self._tabs.setCurrentIndex(self._tabs.currentIndex() + 1)
        else:
            self._tabs.setCurrentIndex(0)
